<template>
    <div class="page">

        <van-nav-bar id="reset" :title="info.name" left-arrow @click-left="backHandle" fixed z-index="100" />
        <div class="pageCon fuPage">


            <div class="conMain">
                <template v-if="msgList.length != 0">
                    <div v-for="(item, index) in msgList" :key="index"
                        :class="item.type == 1 ? 'lineItem reverseItem' : 'lineItem '">
                        <img :src="user.userImg" alt="" v-if="item.type == 1">
                        <img :src="info.userImg || info.doctorPic" alt="" v-if="item.type == 2">
                        <span>{{ item.text }}</span>
                        <span :class="item.type == 1 ? ' timeTipRight' : 'timeTip'">{{ item.time }}</span>
                    </div>
                </template>

                <div v-else class="emptyBox">暂无聊天记录</div>

            </div>
            <div class="inputBox">
                <input type="text" v-model="text" placeholder="请输入内容">
                <div @click="sendHandle(text)">发送</div>
            </div>




        </div>





    </div>
</template>

<script>
import { senMessage } from '../../network/user'
export default {
    name: 'HomeR',
    data() {
        return {
            text: '',
            user: JSON.parse(localStorage.user),
            msgList: [],
            num: 0,
            userId: '',
            doctorId: '',
            socket: null,
            info: '',
        }
    },
    mounted() {
        this.openWeb()

    },
    methods: {
        backHandle() {
            this.$router.back()
        },


        sendHandle(text) {
            var that = this;
            console.log(this.text);
            senMessage({
                userId: this.user.userId,
                doctorId: this.info.id,
                message: text
            }).then(res => {
                if (res.flag) {
                    console.log(res.data.flag);
                    this.$toast('发送成功')
                    console.log(text);
                    this.msgList.push({
                        name: this.user.userName,
                        time: this.getNowDate(),
                        type: 1,
                        text: text
                    })

                    this.saveMsgHandle(this.msgList)
                    if (res.data.flag != 'success') {
                        this.$toast('对方不在线')
                    }

                    this.text = ''


                } else {
                    this.$toast('发送失败，请重试')

                }

            })
        },



        saveMsgHandle(arr) {
            var list = JSON.parse(localStorage.messageList)
            list.forEach(item => {
                if (item.id == this.info.id) {
                    item.msgHistory = arr
                }
            })
            console.log(list);
            localStorage.messageList = JSON.stringify(list)
        },

        openWeb() {
            if (typeof WebSocket == "undefined") {
                this.$toast('不支持')
                console.log("您的设备不支持WebSocket");
            } else {
                this.$toast('支持')
                console.log("您的设备支持WebSocket");
                var _this = this;
                // var socketUrl = "http://192.168.0.107:2035/ws/" + this.user.userId;
                var socketUrl = "wss://www.ccclkj.cn:2035/ws/" + this.user.userId;
                socketUrl = socketUrl.replace("https", "wss").replace("http", "ws");
                console.log(socketUrl);
                if (this.socket != null) {
                    this.socket.close();
                    this.socket = null;
                }
                //打开事件
                _this.socket = new WebSocket(socketUrl);
                //打开事件
                _this.socket.onopen = () => {
                    _this.$toast('聊天室已打开')
                    console.log("websocket已打开");
                };
                //获得消息事件
                _this.socket.onmessage = function (msg) {
                    console.log(msg.data);
                    if (msg.data == "连接成功") {
                        _this.$toast('连接成功')

                    }
                    if (msg.data != "连接成功") {
                        // alert(msg.data)
                        console.log(msg.data);
                        _this.msgList.push({
                            name: _this.info.name,
                            time: _this.getNowDate(),
                            type: 2,
                            text: msg.data
                        })
                        _this.saveMsgHandle(_this.msgList)
                    }
                    //发现消息进入    开始处理前端触发逻辑
                };
                //关闭事件
                _this.socket.onclose = function () {
                    console.log("websocket已关闭");
                };
                //发生了错误事件
                _this.socket.onerror = function () {
                    _this.$toast("连接失败");
                    console.log("websocket发生了错误");
                };
            }
        },

        // 获取当前时间
        getNowDate() {
            var myDate = new Date;
            var year = myDate.getFullYear();
            var mon = myDate.getMonth() + 1;
            mon = mon < 10 ? '0' + mon : mon
            var date = myDate.getDate();
            date = date < 10 ? '0' + date : date
            var date1 = myDate.getDate() + 1;
            date1 = date1 < 10 ? '0' + date1 : date1
            var hours = myDate.getHours();
            hours = hours < 10 ? '0' + hours : hours
            var minutes = myDate.getMinutes();
            minutes = minutes < 10 ? '0' + minutes : minutes
            var seconds = myDate.getSeconds();
            seconds = seconds < 10 ? '0' + seconds : seconds
            // return year + "-" + mon + "-" + date + " " + hours + ':' + minutes + ':' + seconds
            return mon + "-" + date + " " + hours + ':' + minutes + ':' + seconds
        }








    },
    created() {

        this.info = this.$router.history.current.query.info

        this.msgList = this.info.msgHistory
        console.log(this.info);
        console.log(this.msgList);



    },
    //计算属性
    computed: {

    },
    filters: {

    },

}








</script>

<style lang='less' scoped>
.pageCon {
    display: flex;
    align-items: center;
    flex-direction: column;
    box-sizing: border-box;
    position: relative;
    width: 100%;
    height: 100vh;
    background-color: #f0f0f0;
}


#reset /deep/ .van-nav-bar__left .van-nav-bar__text,
#reset /deep/ .van-nav-bar__left .van-icon {
    color: #333 !important;
}


.inputBox {
    // position: absolute;
    // bottom: 0px;
    box-sizing: border-box;
    padding: 0 20px 24px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    background: #f0f0f0;
}

.inputBox>input {
    box-sizing: border-box;
    padding: 0 26px;
    width: 572px;
    height: 72px;
    background: #FFFFFF;
    border-radius: 20px;
    font-family: Source Han Sans CN;
    font-weight: 400;
    font-size: 28px;
    color: #333333;
    outline: none;
    border: none;
}

.inputBox>div {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 110px;
    height: 72px;
    background: linear-gradient(111deg, #14A870, #20BB66);
    border-radius: 20px;
    font-family: Source Han Sans CN;
    font-weight: 400;
    font-size: 28px;
    color: #FFFFFF;
}


.conMain {
    box-sizing: border-box;
    padding: 26px 0;
    width: 100%;
    flex: 1;
    // background: #14A870;
    overflow-y: scroll;
}

.reverseItem {
    flex-direction: row-reverse;
}

.lineItem {
    position: relative;
    margin-bottom: 30px;
    display: flex;
    // align-items: center;
    flex-wrap: nowrap;
    box-sizing: border-box;
    padding: 0 20px 30px;
    width: 100%;
}

.lineItem>img {
    width: 86px;
    height: 86px;
    background: #fff;
    border-radius: 50%;
}

.lineItem>span:nth-child(2) {
    display: inline-block;
    // flex: 1;
    max-width: calc(100% - 200px) !important;
    margin: 0 18px;
    // display: block;
    padding: 26px 28px;
    font-family: Source Han Sans CN;
    font-weight: 400;
    font-size: 28px;
    color: #000000;
    background: #fff;
    border-radius: 18px;
}

.timeTip {
    position: absolute;
    left: 132px;
    bottom: -6px;
    font-size: 28px;
    color: #999;
    z-index: 100;
}

.timeTipRight {
    position: absolute;
    right: 132px;
    bottom: -6px;
    font-size: 28px;
    color: #999;
    z-index: 100;
}

.emptyBox {
    margin-top: 20vh;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    font-size: 28px;
    color: #999;

}
</style>